package com.api.apigateway.init;

import com.api.common.constant.RedisConstant;
import com.api.common.model.dto.ServerDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 崔老爷
 * Date: 2024/10/26 8:55
 * @Description:
 */

@Component
@Slf4j
public class ServerInit {
    @Resource
    private Environment environment;
    @Resource
    private ServerProperties serverProperties;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @PostConstruct
    public void initStoreServerIp() {
        try {
            //获取当前application.yaml中server的端口
            int port = serverProperties.getPort();
            //获取当前服务地址
            InetAddress localHost = InetAddress.getLocalHost();
            String hostAddress = localHost.getHostAddress();
            String hostName = localHost.getHostName();

            ServerDto serverDto = new ServerDto();
            serverDto.setPort(port);
            serverDto.setHostName(hostName);
            serverDto.setHostAddress(hostAddress);
            log.info("初始化Server Store Ip hostAddress={} hostName={} port={}", hostAddress, hostName, port);

            ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
            String serverIpListKey = RedisConstant.SERVER_IP_LIST_KEY;
            final Object o = valueOperations.get(serverIpListKey);
            List<ServerDto> serverDtoList = new ArrayList<>();
            if (o == null) {
                serverDtoList.add(serverDto);
            } else {
                valueOperations.getOperations().delete(serverIpListKey);
                serverDtoList = (List<ServerDto>) o;
                final long count = serverDtoList.stream()
                        .filter(route -> serverDto.getUrl().equals(route.getUrl()))
                        .distinct().count();
                if (count == 0) {
                    serverDtoList.add(serverDto);
                }
            }
            valueOperations.set(serverIpListKey, serverDtoList);

        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }

    }

}
